#! /usr/bin/env python
#coding=utf-8
import  sys,urllib,urllib2,json,time
import MySQLdb
import multiprocessing
reload(sys)

lock = multiprocessing.Lock()

#正式连接-----------
#host = "drdsrtok600s5n74.drds.aliyuncs.com"
#user = "hefantv"
#passwd = "HEfantv3_9a5"
#db = "hefantv"
#测试连接--------------
host = "drdsjsq4v76a23pa.drds.aliyuncs.com"
user = "hefantest"
passwd = "HEfantv3_9a5"
db = "hefantest"
#开发连接--------------
#host = "drdshmif9192k8au.drds.aliyuncs.com"
#user = "hefandev"
#passwd = "devhfDEV8v97"
#db = "hefandev"
port = 3306
charset='utf8'

#
# 获取操作记录数
#
def queryCount() :
    connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
    cursor = connect.cursor()
    sql = "SELECT COUNT(1) FROM live_room"
    cursor.execute(sql)
    data = cursor.fetchone()
    cursor.close()
    connect.close()
    return data[0]

#
# 查询需操作记录【按分页查询】
#
def queryInfoPage(pageSize) :
    beginNum = (pageSize-1)*bachNum
    connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
    cursor = connect.cursor()
    #sql = """select user_id,chat_room_id from live_room where user_id IN ('100000001','1009','1015','1017','1018','1020','1022','1024','1025') order by id limit %d,%d"""%(beginNum,bachNum)
    sql = """select user_id,chat_room_id from live_room order by id limit %d,%d"""%(beginNum,bachNum)
    cursor.execute(sql)
    data = cursor.fetchall()
    cursor.close()
    connect.close()
    return data


#
# 注册融云的聊天室
#
def getRyTokenReq(userId,chartRoomId) :
    if not userId or chartRoomId == 0 :
        return 0
    '''
    reqUrl = url
    data = {"id":chartRoomId,"name":userId}
    #postData = urllib.urlencode([{"id":chartRoomId,"name":userId}])
    postData =  urllib.urlencode(data)
    print postData
    headers = {"Content-Type":"application/json"}
    req = urllib2.Request(reqUrl, postData, headers)
    '''
    reqUrl = "%s?id=%s&name=%s" % (url, chartRoomId, userId)
    req = urllib2.Request(reqUrl)
    res_data = urllib2.urlopen(req,timeout=120)
    resData = json.loads(res_data.read())
    print resData
    time.sleep(0.005)
    if resData["code"] == 1000 :
        return 1
    else:
        return -1

#
# 记录操作结果
#
def saveOpreateResult(saveDatas) :
    connect = MySQLdb.connect(host=host,user=user,passwd=passwd,db=db,port=port,charset=charset)
    cursor = connect.cursor()
    sql = "insert into live_room_his_ry_temp(user_id,res) values " + ",".join(saveDatas)
    cursor.execute(sql)
    connect.commit()
    connect.close()
    cursor.close()

#
# 操作执行方法
#
def opreateMethod(step) :
    infos = queryInfoPage(step)
    saveDatas = []
    for info in infos :
        status = getRyTokenReq(info[0], info[1])
        saveDatas.append("('%s',%d)"%(info[0],status))
        if len(saveDatas) >= bachInsertNum :
            saveOpreateResult(saveDatas)
            saveDatas = []
    if len(saveDatas) > 0 :
        saveOpreateResult(saveDatas)

#url = "http://10.26.241.75:8055/services/imUser/createUser"
#url = "http://10.45.148.233:8055/services/imUser/createUser"
url = "http://127.0.0.1:8055/services/rongIm/createChatroomGet"
bachNum = 1000
bachInsertNum = 500;
if __name__ == "__main__":
    beginTime = time.clock()
    countNum = queryCount()
    step = countNum/bachNum + (1 if countNum%bachNum > 0 else 0)
    print "---"+str(countNum)+"---"+str(step)+"---"
    mgr = multiprocessing.Manager()
    threads = []
    for i in xrange(1,step+1) :
        t_thread = multiprocessing.Process(target=opreateMethod,args=(i,))
        print "-----t_thread start [%d]----" % (i)
        t_thread.start()
        threads.append(t_thread)
    for t_thread in threads :
        t_thread.join()
        print "-----t_thread end----"
    print "chart room ry init end time:%d s" % (time.clock() - beginTime)